package com.mes.spc.service;

import com.mes.entity.User;
import com.mes.spc.rule.*;
import com.mes.spc.util.SPCExcelHead;
import com.mes.spc.util.SPCExcelUtil;
import com.mes.spc.util.SPCExcelWriteUtil;
import com.mes.spc.util.SpcCalUtil;
import com.yy.base.common.dao.Dao;
import com.yy.base.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class EmesqSpcCheckItemConfigService {

	@Autowired
	private Dao dao;
	
	@Autowired
	private EmesqSpcControlChartService chartService;
	
	
	public List<Map<String, Object>> getCheckItemList(String orgId) {
		String sql = "select scp.emesq_spc_checkitem_pro_id, sc.name||'（'|| m.name ||'）' name from Emesq_SPC_CHECKITEM_PRO scp, Emesq_Spc_Checkitem sc,m_product m " +
				" where sc.emesq_spc_checkitem_id=scp.emesq_spc_checkitem_id and scp.m_product_id=m.m_product_id ";
//				" and scp.ad_org_id=?";
		List<Map<String, Object>> data = this.dao.query(sql);
		return data;
	}
	
	public List<Map<String, Object>> getList(String checkNo,String checkItem) {
		List<String> param = new ArrayList<String>();
		String sql = "SELECT cc.Emesq_SPC_CK_CONFIG_ID configId, " +
				"       cc.CODE, " + 
				"       cc.Emesq_SPC_CHECKITEM_PRO_ID, " +
				"       cc.CHECKITEM_TYPE, " + 
				"       cc.GRAPH_TYPE, " + 
				"       cc.SAMPLE_VOLUME, " + 
				"       cc.SPECIFICA_UPPER, " + 
				"       cc.SPECIFICA_LOWER, " + 
				"       cc.TARGET_VAL, " + 
				"       cc.PRECISION, " + 
				"       (select p.name from m_product p where p.m_product_id=cp.m_product_id) productname, " + 
				"       (select c.name from emesq_spc_checkitem c where c.emesq_spc_checkitem_id=cp.emesq_spc_checkitem_id) checkitemname, " + 
				"       to_char(cc.updated, 'yyyy-MM-dd hh24:mi') updateTime, " + 
				"       cc.REMARK " + 
				"  FROM Emesq_SPC_CK_CONFIG cc, emesq_spc_checkitem_pro cp " +
				"  where cc.emesq_spc_checkitem_pro_id=cp.emesq_spc_checkitem_pro_id ";
		if(!StringUtils.isBlank(checkItem)) {
			sql += "     and exists(select 1 from emesq_spc_checkitem c  " + 
				"       where c.emesq_spc_checkitem_id=cp.emesq_spc_checkitem_id " + 
				"          and c.name like ?)";
			param.add("%" + checkItem + "%");
		}
		if(StringUtils.isNotBlank(checkNo)){
			sql +=" and instr(cc.CODE,?)>0 ";
			param.add(checkNo);
		}
		sql += "  order by cc.CODE,cc.created desc ";
		List<Map<String, Object>> data = this.dao.query(sql, param.toArray());
		return data;
	}
	
	public Map<String, Object> getSpcCkConfigById(String id) {
		String sql = "SELECT Emesq_SPC_CK_CONFIG_ID configId, " +
				"       CODE, " + 
				"       Emesq_SPC_CHECKITEM_PRO_ID, " +
				"       CHECKITEM_TYPE, " + 
				"       GRAPH_TYPE, " + 
				"       SAMPLE_VOLUME, " + 
				"       SPECIFICA_UPPER, " + 
				"       SPECIFICA_LOWER, " + 
				"       TARGET_VAL, " +
				"       CONTROL_X_UPPER, " + 
				"       CONTROL_X_LOWER, " + 
				"       CONTROL_X_VAL, " + 
				"		VAL_UPPER,"+
				"		VAL_LOWER,"+
				"       PRECISION, " + 
				"       REMARK, (select to_char(wm_concat(x.code)) excerule_cur " + 
				"		from ( select er.code from Emesq_spc_er_apply era,Emesq_SpC_EXCE_RULE er  " +
				"       where era.emesq_spc_exce_rule_id=er.emesq_spc_exce_rule_id  " + 
				"         and era.emesq_spc_ck_config_id=?" + 
				"         and era.is_valid='Y' " + 
				"   	order by er.code asc) x) er_cur " + 
				"  FROM Emesq_SPC_CK_CONFIG C " +
				" WHERE C.Emesq_SPC_CK_CONFIG_ID = ?";
		Map<String, Object> res = this.dao.queryUnique(sql,id, id);
		return res;
	}

	public String getSysGuid() {
		String sql = "select rawtohex(SYS_GUID()) GUID from dual";
		Map<String, Object> res = this.dao.queryUnique(sql);
		return res.get("GUID") + "";
	}
	
	public int addConfig(Map<String, Object> param) {
		String sql = "insert into emesq_spc_ck_config " + 
				"  (emesq_spc_ck_config_id, code, emesq_spc_checkitem_pro_id, checkitem_type, graph_type, sample_volume, specifica_upper, specifica_lower, target_val, precision, remark,"
				+ "    ad_org_id, ad_client_id, isactive, created, createdby, updated, updatedby,CONTROL_X_UPPER,CONTROL_X_LOWER,CONTROL_X_VAL,VAL_UPPER,VAL_LOWER)" + 
				" values" + 
				"  (:configId, :code, :checkItem, :checkitemType, :graphType, :sampleVolume, :specificaUpper, :specificaLower, :targetVal, :precision, null, "
				+ "    :orgId, :clientId, 'Y', now(), :userId, now(), :userId,:controlXUpper,:controlXLower,:controlX,:valUpper,:valLower)";
		int res = this.dao.executeSql(sql, param);
		return res;
	}

	public int updateConfig(Map<String, Object> param) {
		param.remove("orgId");
		param.remove("clientId");
		String sql = "update emesq_spc_ck_config " + 
				"   set  " + 
				"       code = :code, " + 
				"       emesq_spc_checkitem_pro_id = :checkItem, " + 
				"       checkitem_type = :checkitemType, " + 
				"       graph_type = :graphType, " + 
				"       sample_volume = :sampleVolume, " + 
				"       specifica_upper = :specificaUpper, " + 
				"       specifica_lower = :specificaLower, " + 
				"       target_val = :targetVal, " + 
				"       CONTROL_X_UPPER = :controlXUpper, " + 
				"       CONTROL_X_LOWER = :controlXLower, " + 
				"       CONTROL_X_VAL = :controlX, " + 
				"		VAL_UPPER = :valUpper, "+
				"		VAL_LOWER = :valLower, "+
				"       precision = :precision, " + 
				"       updated = now(), " +
				"       updatedby = :userId " + 
				" where emesq_spc_ck_config_id = :configId";
		return this.dao.executeSql(sql, param);
	}

	/**
	 * 取应用的判异规则
	 * @param configId
	 * @return
	 */
	public List<Map<String, Object>> getErDataApply(String configId){
		String sqlEra = "select era.Emesq_SPC_EXCE_RULE_ID, era.CONTENT, era.var_n, era.var_m, era.var_k, era.is_valid "
				+ " from Emesq_spc_er_apply era "
				+ " where era.emesq_spc_ck_config_id=?";
		List<Map<String, Object>> eraList = this.dao.query(sqlEra, configId);
		return eraList;
	}
	
	public List<Map<String, Object>> getErData(String configId, String graphType) {
		String sql = "select er.Emesq_SPC_EXCE_RULE_ID, er.CONTENT, er.code, er.VAR_N, er.VAR_M, er.VAR_K, er.basis "
				+ " from Emesq_SpC_EXCE_RULE er "
				+ " order by er.code asc ";
		List<Map<String, Object>> list = this.dao.query(sql);
		List<Map<String, Object>> eraList= getErDataApply(configId);
		HashMap<String, Map<String, Object>> eraMap = new HashMap<String, Map<String, Object>>();
		for (Map<String, Object> map : eraList) {
			eraMap.put("" + map.get("Emesq_SPC_EXCE_RULE_ID"), map);
		}
		
		List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
		//合并当前规则到规则列表
		for (Map<String, Object> map : list) {
			Map<String, Object> cur = eraMap.get( "" + map.get("Emesq_SPC_EXCE_RULE_ID"));
			if(cur != null) {
				map.put("CONTENT", cur.get("CONTENT"));
				map.put("VAR_N", cur.get("VAR_N"));
				map.put("VAR_M", cur.get("VAR_M"));
				map.put("VAR_K", cur.get("VAR_K"));
				map.put("IS_VALID", cur.get("IS_VALID"));
			}
			if("nP".equals(graphType) || "C".equals(graphType) ||"P".equals(graphType) || "U".equals(graphType)) {	//计数型图类，仅应用R1，R2 ，R3, R4规则
				String code = map.get("CODE") + "";
				if("R1".equals(code) || "R2".equals(code) || "R3".equals(code) || "R4".equals(code)) {
					res.add(map);
				}
			} else {
				res.add(map);
			}
		}
		return res;
	}

	public int saveExceRuleData(String exceRuleData, String configId, String orgId, User user) {
		JSONArray jsonArr = JSONArray.fromObject(exceRuleData);
		List<Map<String, Object>> list = (List<Map<String, Object>>) JSONArray.toCollection(jsonArr, HashMap.class);
		System.err.println(list);
		String delSql = "delete Emesq_spc_er_apply where Emesq_SPC_CK_CONFIG_ID=? ";
		this.dao.executeSql(delSql, configId);
		String insSql = "insert into emesq_spc_er_apply " + 
				"  (emesq_spc_er_apply_id, emesq_spc_exce_rule_id, emesq_spc_ck_config_id, content, var_n, var_m, var_k, is_valid,"
				+ "  ad_org_id, ad_client_id, isactive, created, createdby, updated, updatedby) "
				+ " values"
				+ "  (SYS_GUID(), ?, ?, ?, decode(?, -1, null, ?),  decode(?, -1, null, ?),  decode(?, -1, null, ?), ?, "
				+ "   ?, ?, 'Y', now(), ?, now(), ?) ";
		for (Map<String, Object> map : list) {
			if("Y".equals(map.get("IS_VALID"))) {
				this.dao.executeSql(insSql, map.get("Emesq_SPC_EXCE_RULE_ID"), configId, map.get("CONTENT"),
						map.get("VAR_N") instanceof JSONNull ? -1 : map.get("VAR_N"), map.get("VAR_N"),
						map.get("VAR_M") instanceof JSONNull ? -1 : map.get("VAR_M"), map.get("VAR_M"), 
						map.get("VAR_K") instanceof JSONNull ? -1 : map.get("VAR_K"), map.get("VAR_K"),
						map.get("IS_VALID"),
						orgId, user.getClientId(), user.getId(), user.getId());
			}
		}
		return 1;
	}
	
	/**
	 * 取不良类型
	 * @param configId
	 * @return
	 */
	public List<Map<String, Object>> getBadProductData(String configId) {
		String sql = "select pr.emesq_quality_poor_reason_id, pr.code, pr.name  " + 
				" from Emesq_QUALITY_POOR_REASON pr " +
				" where pr.isactive='Y' " + 
				" and pr.PARENT_ID is not null " + 
				" and not exists(select 1 from Emesq_SPC_BADPRODUCT b " +
				"    where b.emesq_quality_poor_reason_id=pr.emesq_quality_poor_reason_id " + 
				"    and b.emesq_spc_ck_config_id=? )" +
				" order by pr.code asc";
		List<Map<String, Object>> data = this.dao.query(sql, configId);
		return data;
	}

	/**
	 * 选中的不良类型
	 * @param configId
	 * @return
	 */
	public List<Map<String, Object>> getBadProductSelData(String configId) {
		String sql = "select b.emesq_spc_badproduct_id, b.emesq_quality_poor_reason_id, pr.code, pr.name  " + 
				" from Emesq_SPC_BADPRODUCT b, Emesq_QUALITY_POOR_REASON pr  " +
				" where b.emesq_quality_poor_reason_id=pr.emesq_quality_poor_reason_id  " + 
				" and b.emesq_spc_ck_config_id=?";
		List<Map<String, Object>> data = this.dao.query(sql, configId);
		return data;
	}
	
	public void saveBadProductData(String badProductData, String configId, String orgId, User user) {
		JSONArray jsonArr = JSONArray.fromObject(badProductData);
		List<Map<String, Object>> list = (List<Map<String, Object>>) JSONArray.toCollection(jsonArr, HashMap.class);
		String delSql = "delete Emesq_SPC_BADPRODUCT where Emesq_SPC_CK_CONFIG_ID=? ";
		this.dao.executeSql(delSql, configId);
		String insSql = "insert into emesq_spc_badproduct " + 
				"  (emesq_spc_badproduct_id, emesq_spc_ck_config_id, emesq_quality_poor_reason_id, remark, "
				+ "  ad_org_id, ad_client_id, isactive, created, createdby, updated, updatedby)" + 
				" values " + 
				"  (SYS_GUID(), ?, ?, '', "
				+ " ?, ?, 'Y', now(), ?, now(), ?)";
		for (Map<String, Object> map : list) {
			this.dao.executeSql(insSql, configId, map.get("Emesq_QUALITY_POOR_REASON_ID"),
					orgId, user.getClientId(), user.getId(), user.getId());
		}
	}
	
	@Transactional
	public int handleExcel(User user,String orgId,String configId,String isSampleData, File file) throws Exception{
		Map<String, Object> ckConfig = getSpcCkConfigById(configId);
		if(ckConfig==null){
			throw new Exception("检测项目ID错误！");
		}
		int importCount = 0;
		SPCExcelUtil excelUtil = new SPCExcelUtil();
		List<String[]> strs = excelUtil.parseExcel(file);
		String[] tableHeadArray = strs.get(0);//表头列
		String tableHeadStr = ArrayUtils.toString(tableHeadArray);
		String checkItemType = ckConfig.get("CHECKITEM_TYPE")+"";//检测类型 variables 计量  counting  计数
		String graphType = ckConfig.get("GRAPH_TYPE")+"";//图表类型
		if(user==null){
			user = new User();
			user.setClientId("109695EA6D204270953EBF6EC5731DBD");
			user.setId("6929345FF3A5451C9BD585DA725A7758");
		}
		if (orgId==null)orgId="7B441EB01848477687A8ADE94F1F5F2A";

		if(graphType.equals("XR")||graphType.equals("XS")||graphType.equals("MR")||graphType.equals("IMR")) {
			if(!tableHeadStr.contains("抽检时间")||!tableHeadStr.contains("样本")){
				throw new Exception("模板不匹配!");
			}
			if(ckConfig.get("SAMPLE_VOLUME")==null){
				throw new Exception("未设置样本容量!");
			}
			int sampleSize = Integer.parseInt(ckConfig.get("SAMPLE_VOLUME")+"");//样本数量
			int countSample = 0;
			List<Integer> ss = new ArrayList<Integer>();
			for(int i = 0;i<tableHeadArray.length;i++){
				String str = tableHeadArray[i];
				if(str.startsWith("样本")){
					ss.add(i);
					countSample++;
				}
			}
			if(countSample!=sampleSize){
				throw new Exception("样本数不匹配!");
			}
			int jrCount=0;
			double tempLastVal = 0;
			p:for(String[] sa:strs){
				//取样本值
				double[] groupSampleData = new double[ss.size()];
				boolean checkFlag = true;
				for(int i =0;i<ss.size();i++){
					if(SpcCalUtil.isDouble(sa[ss.get(i)])) {
						groupSampleData[i] = Double.parseDouble(sa[ss.get(i)]);
					}else{
						//样本数据不符合规则直接跳过本条数据
						continue p;
					}
				}
				String checkDate = sa[0];
				double avgNum = SpcCalUtil.avage(groupSampleData);//均值
				double stdNum = sampleSize==1?0:SpcCalUtil.stDev(groupSampleData);//标准差
				double maxNum = SpcCalUtil.max(groupSampleData);//最大值
				double minNum = SpcCalUtil.min(groupSampleData);//最小值
				double rNum = maxNum-minNum;//极差
				//当为单值时，极差算法为上值与下值的差
				//IMR图 极差算法不一致
				if(graphType.equals("IMR")) {
					if (jrCount == 0) {
						rNum = 0;
					} else {
						rNum = Math.abs(tempLastVal - groupSampleData[0]);
					}
					tempLastVal =groupSampleData[0];//记录上一个值
					jrCount++;
				}
				//插入数据 Emesq_SPC_SAMPLE_CALC
				String getCalId = StringUtil.getUUID();
				int insertflag = insertSampleCalcForVar(getCalId,configId,checkDate,user,orgId,avgNum,stdNum,maxNum,minNum,rNum,isSampleData,sampleSize);
				//插入数据 Emesq_SPC_SAMPLE_VALUE
				if(insertflag>0){
					insertflag = insertSampleCalcValueForVar(getCalId,groupSampleData,user,orgId);
				}
				if(insertflag>0)importCount++;
			}
		}else{
			String sql = "select r.name RNAME,r.code RCODE from Emesq_SPC_BADPRODUCT t,Emesq_QUALITY_POOR_REASON r " +
					"where 1=1 " +
					"and t.emesq_quality_poor_reason_id=r.emesq_quality_poor_reason_id " +
					"and t.emesq_spc_ck_config_id=?";
			List<Map<String, Object>> cols = dao.query(sql,configId);//不良列
			//检查表头数据
//			String[] checkStr = new String[cols.size()+2];
//			checkStr[0]="抽检时间";
//			checkStr[1]="抽检数";
			Map<String,String> codeNameMap = new HashMap<String,String>();
			codeNameMap.put("抽检时间","");
			codeNameMap.put("抽检数","");
			for(int i = 0;i<cols.size();i++){
//				checkStr[i+2]=cols.get(i).get("RNAME")+"";
				codeNameMap.put(cols.get(i).get("RNAME")+"",cols.get(i).get("RCODE")+"");
			}
			//检查表头数据是否对应
			Map<String,Integer> nameIndexMap = new HashMap<String,Integer>();
			for(int i = 0;i<tableHeadArray.length;i++){
				if(codeNameMap.get(tableHeadArray[i])!=null){
					nameIndexMap.put(tableHeadArray[i],i);
				}
			}
			if(nameIndexMap.size()!=codeNameMap.size())throw new Exception("模板列与定义的不良项目不匹配！");
			int count = 0;
			p:for(String[] sa:strs){
				if(count==0){
					count++;
					continue;
				}
				String checkDate = sa[nameIndexMap.get("抽检时间")];
				String checkCount = sa[nameIndexMap.get("抽检数")];
				if(!SpcCalUtil.isDouble(checkCount)){continue p;}
				//插入数据 Emesq_SPC_SAMPLE_CALC
				String getCalId = StringUtil.getUUID();
				int insertflag = insertSampleCalcForCount(getCalId,configId,checkDate,user,orgId,checkCount,isSampleData);
				//插入数据 Emesq_SPC_SAMPLE_VALUE
				if(insertflag>0){
					insertflag = insertSampleCalcValueForCount(getCalId,sa,nameIndexMap,codeNameMap,user,orgId);
				}
				if(insertflag>0)importCount++;
			}
		}
		file.delete();
		return importCount;
	}

	public void downloadExcelTemplate(HttpServletResponse response,String configId){
		try {
			Map<String, Object> ckConfig = getSpcCkConfigById(configId);
			if(ckConfig==null){
				throw new Exception("检测项目ID错误！");
			}
			String checkItemType = ckConfig.get("CHECKITEM_TYPE")+"";//检测类型 variables 计量  counting  计数
			String graphType = ckConfig.get("GRAPH_TYPE")+"";//图表类型
			String code = ckConfig.get("CODE")+"";//编码
			SPCExcelHead[][] heads = null;
			String fileName = "";
			if(graphType.equals("XR")||graphType.equals("XS")||graphType.equals("MR")||graphType.equals("IMR")) {
				if(ckConfig.get("SAMPLE_VOLUME")==null)throw new Exception("未设置样本容量！");
				int sampleSize = Integer.parseInt(ckConfig.get("SAMPLE_VOLUME")+"");//样本数量
				fileName = "计量模板";
				heads = new SPCExcelHead[1][sampleSize+1];
				heads[0][0] = new SPCExcelHead("抽检时间");//固定列
				for (int j = 1; j < heads[0].length; j++) {
					heads[0][j] = new SPCExcelHead("样本"+j);
				}
			}else{
				fileName = "计数模板";
				String sql = "select r.name RNAME,r.code RCODE from Emesq_SPC_BADPRODUCT t,Emesq_QUALITY_POOR_REASON r " +
						"where 1=1 " +
						"and t.emesq_quality_poor_reason_id=r.emesq_quality_poor_reason_id " +
						"and t.emesq_spc_ck_config_id=?";
				List<Map<String, Object>> cols = dao.query(sql,configId);//不良列
				heads = new SPCExcelHead[1][cols.size()+2];
				heads[0][0] = new SPCExcelHead("抽检时间");//固定列
				heads[0][1] = new SPCExcelHead("抽检数");//固定列
				for(int i=0;i<cols.size();i++){
					heads[0][i+2] = new SPCExcelHead(cols.get(i).get("RNAME")+"");
				}
			}
			fileName+="，编码为："+code+"，图表类型："+graphType;
			SPCExcelWriteUtil util = new SPCExcelWriteUtil();
			util.createExcel();
			util.createHead(heads);
			util.writeFileToResponse(response,fileName+"—"+new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public int insertSampleCalcForVar(String getCalId, String configId, String checkDate, User user, String orgId,
									   double avgNum, double stdNum,
									   double maxNum, double minNum,
									   double rNum,String isSample,int sampleSize){
	    String dateFormat = "yyyy-MM-dd hh24:mi:ss";
	    if(checkDate.contains("/")){
            dateFormat = "yyyy/MM/dd hh24:mi:ss";
        }
	    if(isSample.equals("1")){
	    	isSample = "Y";
	    }else{
	    	isSample = "N";
	    }
		String sql = "insert into Emesq_SPC_SAMPLE_CALC " +
				"(Emesq_SPC_SAMPLE_CALC_ID, Emesq_SPC_CK_CONFIG_ID, CHECK_DATE, CHECK_COUNT, STATE, AVG, RANGE, STANDARD_DEVIATION, MAX_VALUE, MIN_VALUE, AD_ORG_ID, AD_CLIENT_ID, ISACTIVE, CREATED, CREATEDBY, UPDATED, UPDATEDBY, IS_CONTROL, IS_SAMPLE) " +
				"values" +
				"('"+getCalId+"', '"+configId+"', to_date('"+checkDate+"','"+dateFormat+"'), "+sampleSize+", null, "+avgNum+", "+rNum+", "+stdNum+", "+maxNum+", "+minNum+", '"+orgId+"', '"+user.getClientId()+"', 'Y', now(), '"+user.getId()+"', sysdate, '"+user.getId()+"',null,'"+isSample+"')";
		return dao.executeSql(sql);
	}

	public int insertSampleCalcValueForVar(String calcId, double[] sampleData, User user, String orgId){
		String sql = "insert into Emesq_SPC_SAMPLE_VALUE " +
				"(Emesq_SPC_SAMPLE_VALUE_ID, Emesq_SPC_SAMPLE_CALC_ID, VALUE, CODE, NAME, SAMPLE_NO, AD_ORG_ID, AD_CLIENT_ID, ISACTIVE, CREATED, CREATEDBY, UPDATED, UPDATEDBY) " +
				"values" +
				"(sys_guid(), '"+calcId+"',?, null, null, null, '"+orgId+"', '"+user.getClientId()+"', 'Y', now(), '"+user.getId()+"', now(), '"+user.getId()+"')";
		int insertCount = 0;
		for(double sd:sampleData){
			insertCount+=dao.executeSql(sql,sd);
		}
		return insertCount;
	}

	public int insertSampleCalcForCount(String getCalId, String configId, String checkDate, User user, String orgId,String checkCount,String isSample){
		String dateFormat = "yyyy-MM-dd hh24:mi:ss";
		if(checkDate.contains("/")){
			dateFormat = "yyyy/MM/dd hh24:mi:ss";
		}
		if(isSample.equals("1")){
	    	isSample = "Y";
	    }else{
	    	isSample = "N";
	    }
		String sql = "insert into Emesq_SPC_SAMPLE_CALC " +
				"(Emesq_SPC_SAMPLE_CALC_ID, Emesq_SPC_CK_CONFIG_ID, CHECK_DATE, CHECK_COUNT, STATE, AVG, RANGE, STANDARD_DEVIATION, MAX_VALUE, MIN_VALUE, AD_ORG_ID, AD_CLIENT_ID, ISACTIVE, CREATED, CREATEDBY, UPDATED, UPDATEDBY, IS_CONTROL, IS_SAMPLE) " +
				"values" +
				"('"+getCalId+"', '"+configId+"', to_date('"+checkDate+"','"+dateFormat+"'), "+checkCount+", null, null, null, null, null, null, '"+orgId+"', '"+user.getClientId()+"', 'Y', now(), '"+user.getId()+"', sysdate, '"+user.getId()+"',null,'"+isSample+"')";
		return dao.executeSql(sql);
	}

	public int insertSampleCalcValueForCount(String calcId,String[] sa,Map<String,Integer> nameIndexMap,Map<String,String> codeNameMap,User user, String orgId){
		String sql = "insert into Emesq_SPC_SAMPLE_VALUE " +
				"(Emesq_SPC_SAMPLE_VALUE_ID, Emesq_SPC_SAMPLE_CALC_ID, VALUE, CODE, NAME, SAMPLE_NO, AD_ORG_ID, AD_CLIENT_ID, ISACTIVE, CREATED, CREATEDBY, UPDATED, UPDATEDBY) " +
				"values" +
				"(sys_guid(), '"+calcId+"',?, ?, null, null, '"+orgId+"', '"+user.getClientId()+"', 'Y', now(), '"+user.getId()+"', now(), '"+user.getId()+"')";
		int insertCount = 0;
		for(String sd:codeNameMap.keySet()){
			if(!codeNameMap.get(sd).equals("")) {
				insertCount += dao.executeSql(sql,StringUtils.defaultIfEmpty(sa[nameIndexMap.get(sd)],"0"),codeNameMap.get(sd));
			}
		}
		return insertCount;
	}
	
	public int insertSampleCalcValueForCount(String calcId,String[] sa,String[] codes,User user, String orgId){
		String sql = "insert into Emesq_SPC_SAMPLE_VALUE " +
				"(Emesq_SPC_SAMPLE_VALUE_ID, Emesq_SPC_SAMPLE_CALC_ID, VALUE, CODE, NAME, SAMPLE_NO, AD_ORG_ID, AD_CLIENT_ID, ISACTIVE, CREATED, CREATEDBY, UPDATED, UPDATEDBY) " +
				"values" +
				"(sys_guid(), '"+calcId+"',?, ?, null, null, '"+orgId+"', '"+user.getClientId()+"', 'Y', now(), '"+user.getId()+"', now(), '"+user.getId()+"')";
		int insertCount = 0;
		for(int i =0;i<sa.length;i++){
				insertCount += dao.executeSql(sql,StringUtils.defaultIfEmpty(sa[i],"0"),codes[i]);
		}
		return insertCount;
	}
	
	public boolean updateSampleCalcData(String getCalId, String configId, String checkDate, User user, String orgId,
			   double avgNum, double stdNum,
			   double maxNum, double minNum,
			   double rNum,String isSample){
		String dateFormat = "yyyy-MM-dd hh24:mi:ss";
	    if(checkDate.contains("/")){
            dateFormat = "yyyy/MM/dd hh24:mi:ss";
        }
	    if(isSample.equals("1")){
	    	isSample = "Y";
	    }else{
	    	isSample = "N";
	    }
		String sql = "update Emesq_SPC_SAMPLE_CALC set CHECK_DATE=to_date('"+checkDate+"','"+dateFormat+"'),AVG=?,RANGE=?,STANDARD_DEVIATION=?,MAX_VALUE=?,MIN_VALUE=?,IS_SAMPLE=? where Emesq_SPC_SAMPLE_CALC_ID=?";
		int r1 = dao.executeSql(sql, avgNum,rNum,stdNum,maxNum,minNum,isSample,getCalId);
		//清除值数据
		deleteSampleValueData(getCalId);
		return r1>0;
	}
	
	public Map<String,Object> getConfig(String configId){
		String sql = "select * from emesq_spc_ck_config where Emesq_SPC_CK_CONFIG_ID=?";
		return dao.queryUnique(sql, configId);
	}
	
	public boolean setConfig(String configId,double usl,double lsl,double target){
		String sql = "update emesq_spc_ck_config set SPECIFICA_UPPER=?,SPECIFICA_LOWER=?,TARGET_VAL=? where Emesq_SPC_CK_CONFIG_ID=?";
		return dao.executeSql(sql, usl,lsl,target,configId)>0;
	}
	
	public boolean setControl(String configId,double ucl,double lcl,double target){
		String sql = "update emesq_spc_ck_config set CONTROL_X_UPPER=?,CONTROL_X_LOWER=?,CONTROL_X_VAL=? where Emesq_SPC_CK_CONFIG_ID=?";
		return dao.executeSql(sql, ucl,lcl,target,configId)>0;
	}
	
	//查询应用的判异规则
	public List<Map<String,Object>> getApplyRules(String configId){
		String sql = "select eser.code,esea.content,esea.var_n,esea.var_m,esea.var_k from Emesq_spc_er_apply esea,emesq_spc_exce_rule eser"+
					" where 1=1"+
					" and esea.emesq_spc_exce_rule_id=eser.emesq_spc_exce_rule_id"+
					" and esea.emesq_spc_ck_config_id=?";
		return dao.query(sql, configId);
	}
	
	//执行判异规则过程 计数型
	public void executeCountCheckRule(String configId,List<String> calcIdList,List<Double> badCountList,
			double ucl,double lcl,double cl,User user,String orgId) throws Exception{
		List<Map<String,Object>> rules = getApplyRules(configId);
		if(rules==null||rules.size()==0)throw new Exception("未设置判异规则！");
		List<SPCCommandbase> result = new ArrayList<SPCCommandbase>();
		for(Map<String,Object> r:rules){
			if(r.get("CODE")!=null){
				if(r.get("CODE").equals("R1")){
					result.add(new SpcRule1());
				}
				else if(r.get("CODE").equals("R2")){
					result.add(new SpcRule2());
				}
				else if(r.get("CODE").equals("R3")){
					result.add(new SpcRule3());
				}
				else if(r.get("CODE").equals("R4")){
					result.add(new SpcRule4());
				}
			}
		}
		if(result.size()==0)throw new Exception("未设置判异规则！");
		double tempUcl = (ucl-lcl)/2d;//临时ucl
        double tempLcl = -1d*tempUcl;//临时lcl
        SPCDetermineMethod method = new SPCDetermineMethod(0,0,tempUcl, tempLcl,cl,result);
        for(int i=0;i<badCountList.size();i++){
        	Double s = badCountList.get(i);
            List<SPCCommandbase> rs = method.Excute(s);
            String checkResult = "检测结果：";
            for(SPCCommandbase spccd:rs){
                checkResult+=spccd.getTitle()+"---"+spccd.getDescription()+"<br/>";
            }
//            System.out.println("-------------------------");
            String state = "正常";
            //删除历史判异记录
            deleteCheckDataByCalId(calcIdList.get(i));
            if(rs.size()>0){//存在则出现异常数据
            	state = "异常";
            	addCheckRecord(calcIdList.get(i), checkResult, user, orgId);
            }else{
            	
            }
            String updateCalcSql = "update Emesq_SPC_SAMPLE_CALC set STATE=? where Emesq_SPC_SAMPLE_CALC_ID=?";
            if(dao.executeSql(updateCalcSql, state,calcIdList.get(i))<=0){
            	throw new Exception("数据错误！");
            }
        }
	}
	//执行判异规则过程 计量型
	public void executeCheckRule(String configId,String[] calcIdArray,double[] avgArray, double usl, double lsl,double ucl,double lcl,double cl,User user,String orgId) throws Exception{
		List<Map<String,Object>> rules = getApplyRules(configId);
		if(rules==null||rules.size()==0)throw new Exception("未设置判异规则！");
		List<SPCCommandbase> result = new ArrayList<SPCCommandbase>();
		for(Map<String,Object> r:rules){
			if(r.get("CODE")!=null){
				if(r.get("CODE").equals("R0")){
					if(usl!=SpcCalUtil.ErrNum&&lsl!=SpcCalUtil.ErrNum){
						result.add(new SpcRule0());
					}
				}
				else if(r.get("CODE").equals("R1")){
					result.add(new SpcRule1());
				}
				else if(r.get("CODE").equals("R2")){
					result.add(new SpcRule2());
				}
				else if(r.get("CODE").equals("R3")){
					result.add(new SpcRule3());
				}
				else if(r.get("CODE").equals("R4")){
					result.add(new SpcRule4());
				}
				else if(r.get("CODE").equals("R5")){
					result.add(new SpcRule5());
				}
				else if(r.get("CODE").equals("R6")){
					result.add(new SpcRule6());
				}
				else if(r.get("CODE").equals("R7")){
					result.add(new SpcRule7());
				}
				else if(r.get("CODE").equals("R8")){
					result.add(new SpcRule8());
				}
			}
		}
		if(result.size()==0)throw new Exception("未设置判异规则！");
		
		double tempUcl = (ucl-lcl)/2d;//临时ucl
        double tempLcl = -1d*tempUcl;//临时lcl
        SPCDetermineMethod method = new SPCDetermineMethod(usl,lsl,tempUcl, tempLcl,cl,result);
        for(int i=0;i<avgArray.length;i++){
        	double s = avgArray[i];
            List<SPCCommandbase> rs = method.Excute(s);
//            System.out.println("检测值："+s);
            String checkResult = "检测结果：<br/>";
            for(SPCCommandbase spccd:rs){
//                System.out.println("检测值："+s+"---"+spccd.getTitle()+"---"+spccd.toString());
                checkResult+=spccd.getTitle()+"---"+spccd.getDescription()+"<br/>";
            }
//            System.out.println("-------------------------");
            String state = "正常";
            //删除历史判异记录
            deleteCheckDataByCalId(calcIdArray[i]);
            if(rs.size()>0){//存在则出现异常数据
            	state = "异常";
            	addCheckRecord(calcIdArray[i], checkResult, user, orgId);
            }else{
            	
            }
            String updateCalcSql = "update Emesq_SPC_SAMPLE_CALC set STATE=? where Emesq_SPC_SAMPLE_CALC_ID=?";
            if(dao.executeSql(updateCalcSql, state,calcIdArray[i])<=0){
            	throw new Exception("数据错误！");
            }
        }
	}
	
	/**
	 * 执行判异规则
	 * @param configId
	 * @param user
	 * @param orgId
	 * @throws Exception 
	 */
	public void executeCheckRule(String configId,User user,String orgId,String scDate,Map<String,String> paramMap) throws Exception{
		double UCL = 0d;//控制上限
        double LCL = 0d;//控制下限
        double CL = 0d;//控制中线 所有样本均值
        
        Map<String, Object> ckConfig = getSpcCkConfigById(configId);
        //查询当前控制上下限是否已经设置
        String cxu = ckConfig.get("CONTROL_X_UPPER")==null?"":(ckConfig.get("CONTROL_X_UPPER")+"");
        String cxl = ckConfig.get("CONTROL_X_LOWER")==null?"":(ckConfig.get("CONTROL_X_LOWER")+"");
        String cx = ckConfig.get("CONTROL_X_VAL")==null?"":(ckConfig.get("CONTROL_X_VAL")+"");
        
        //图标类型
        String graphType = ckConfig.get("GRAPH_TYPE")+"";
        if(graphType.equals("P")||graphType.equals("U")||
        		graphType.equals("C")||graphType.equals("nP")){//计数型
        	Map<String, Object> ts = chartService.getBadProductData(ckConfig, configId,false,scDate,paramMap);
        	CL = (Double)ts.get("cl");
        	UCL = (Double)ts.get("rucl");
        	LCL = (Double)ts.get("rlcl");
        	if(CL==0d&&UCL==0d&&LCL==0d){
        		throw new Exception("未查到样本数据，无法计算！");
        	}
        	List<Double> badCountList = null;
        	List<String> calcIdList = (List<String>)ts.get("calcIdList");
        	if("P".equals(graphType) || "U".equals(graphType)) {//比较比率
        		badCountList = (List<Double>)ts.get("badRateList");
    		}else{//比较数量
    			badCountList = (List<Double>)ts.get("badCountList");
    		}
    		if(StringUtils.isNotEmpty(cxu)&&StringUtils.isNotEmpty(cxl)&&StringUtils.isNotEmpty(cx)){
    			CL = Double.parseDouble(cx);
    			UCL = Double.parseDouble(cxu);
    			LCL = Double.parseDouble(cxl);
    		}
			executeCountCheckRule(configId,calcIdList, badCountList, UCL, LCL, CL, user, orgId);
			
        }else{//计量型
        	Map<String, Object> arrayDataMap = chartService.getSampleArrayData(ckConfig,configId,scDate,paramMap);
            if(checkData(arrayDataMap)){
            	throw new Exception("未查到样本数据！");
            }
            double[] avgArray = ArrayUtils.toPrimitive((Double[])arrayDataMap.get("avgArray"));//样本均值
            double[] avgRArray = ArrayUtils.toPrimitive((Double[])arrayDataMap.get("avgRArray"));//极差平均值
            double[] stdevArray = ArrayUtils.toPrimitive((Double[])arrayDataMap.get("avgStdevArray"));//标准差均值
            String[] calcIdArray = (String[])arrayDataMap.get("calcIdArray");//样本ID的集合;
            double[] arrData = ArrayUtils.toPrimitive((Double[])arrayDataMap.get("arrData"));//所有样本
            int sampleSize = Integer.parseInt(ckConfig.get("SAMPLE_VOLUME")+"");//样本容量
            double LSL = Double.parseDouble(ckConfig.get("SPECIFICA_LOWER")==null?SpcCalUtil.ErrNum +"":(ckConfig.get("SPECIFICA_LOWER")+""));
            double USL =  Double.parseDouble(ckConfig.get("SPECIFICA_UPPER")==null?SpcCalUtil.ErrNum +"":(ckConfig.get("SPECIFICA_UPPER")+""));
            
            double CL_R = SpcCalUtil.avage(avgRArray);//极差平均值
            //根据图形计算控制线上下值
            if(ckConfig.get("GRAPH_TYPE").equals("IMR")){
            	double sumJc = 0d;//移动极差的和
                for(int i = 1;i<avgArray.length;i++){
                    sumJc+=Math.max(avgArray[i],avgArray[i-1])-Math.min(avgArray[i],avgArray[i-1]);
                }
                int w = 2;//移动极差的长度。默认值为 2。
                double avgSumJc = sumJc/((avgArray.length-w+1)*1d);//移动极差平均值
                double stdev = avgSumJc/SpcCalUtil.D2ConstantNum[w-2];

                CL = SpcCalUtil.avage(avgArray);//样板平均值
                //计算均值
                UCL = CL+stdev*3;
                LCL = CL-stdev*3;
            }else{
    	        CL = SpcCalUtil.avage(avgArray);//样板平均值
    	        //计算均值
    	        UCL = SpcCalUtil.ZeroFormat(CL+SpcCalUtil.A2ConstantNum[sampleSize-2]*CL_R,3);
    	        LCL = SpcCalUtil.ZeroFormat(CL-SpcCalUtil.A2ConstantNum[sampleSize-2]*CL_R,3);
            }
        	if(StringUtils.isNotEmpty(cxu)&&StringUtils.isNotEmpty(cxl)&&StringUtils.isNotEmpty(cx)){
    			CL = Double.parseDouble(cx);
    			UCL = Double.parseDouble(cxu);
    			LCL = Double.parseDouble(cxl);
    		}
			executeCheckRule(configId, calcIdArray, avgArray, USL, LSL, UCL, LCL, CL,user,orgId);
        }
	}
	
	//新增判异规则检查出来的结果
	private int addCheckRecord(String calcId,String result,User user,String orgId){
		String sql = "insert into Emesq_SPC_SAMPLE_CHECK(Emesq_SPC_SAMPLE_CHECK_ID, Emesq_SPC_SAMPLE_CALC_ID, ERROR_INFO, AD_ORG_ID, AD_CLIENT_ID, ISACTIVE, CREATED, CREATEDBY, UPDATED, UPDATEDBY)"+
				"values(sys_guid(),?,?,?,?,?,now(),?,now(),?)";
		return dao.executeSql(sql, calcId,result,orgId,user.getClientId(),"Y",user.getId(),user.getId());
	}
	
	/**
	 * 计算控制限的值
	 * @param confidId
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> calControl(String confidId,Map<String,String> paramMap) throws Exception{
		if(StringUtils.isEmpty(confidId)){
			throw new Exception("缺少必要参数");
		}
		Map<String, Object> ckConfig = getSpcCkConfigById(confidId);
        int p = NumberUtils.toInt("" + ckConfig.get("PRECISION"));//小数位数
        
        double UCL = 0d;//控制上限
        double LCL = 0d;//控制下限
        double CL = 0d;//控制中线 所有样本均值
        String graphType = ckConfig.get("GRAPH_TYPE")+"";
        
        if(ckConfig.get("GRAPH_TYPE").equals("P")||
        		ckConfig.get("GRAPH_TYPE").equals("U")||
        		ckConfig.get("GRAPH_TYPE").equals("C")||
        		ckConfig.get("GRAPH_TYPE").equals("nP")){//计数型
        	Map<String, Object> ts = chartService.getBadProductData(ckConfig, confidId,true,"",paramMap);
        	CL = (Double)ts.get("cl");
        	UCL = (Double)ts.get("ucl");
        	LCL = (Double)ts.get("lcl");
        	if(CL==0d&&UCL==0d&&LCL==0d){
        		throw new Exception("未查到样本数据，无法计算！");
        	}
        	
        }else{//计量型
        	Map<String,Object> sampleArryData = chartService.getSampleArrayData(ckConfig, confidId, true,"",paramMap);
    		if(checkData(sampleArryData)){
    			throw new Exception("未查到样本数据，无法计算！");
            }
            double[] avgArray = ArrayUtils.toPrimitive((Double[])sampleArryData.get("avgArray"));//样本均值
            double[] avgRArray = ArrayUtils.toPrimitive((Double[])sampleArryData.get("avgRArray"));//极差平均值
            double[] stdevArray = ArrayUtils.toPrimitive((Double[])sampleArryData.get("avgStdevArray"));//标准差均值
            String[] calcIdArray = (String[])sampleArryData.get("calcIdArray");//样本ID的集合;
            double[] arrData = ArrayUtils.toPrimitive((Double[])sampleArryData.get("arrData"));//所有样本
            int sampleSize = Integer.parseInt(ckConfig.get("SAMPLE_VOLUME")+"");//样本容量
            double LSL = Double.parseDouble(ckConfig.get("SPECIFICA_LOWER")==null?SpcCalUtil.ErrNum +"":(ckConfig.get("SPECIFICA_LOWER")+""));
            double USL =  Double.parseDouble(ckConfig.get("SPECIFICA_UPPER")==null?SpcCalUtil.ErrNum +"":(ckConfig.get("SPECIFICA_UPPER")+""));
            double CL_R = SpcCalUtil.avage(avgRArray);//极差平均值
            //根据图形计算控制线上下值 
	        if(graphType.equals("IMR")){
	        	double sumJc = 0d;//移动极差的和
	            for(int i = 1;i<avgArray.length;i++){
	                sumJc+=Math.max(avgArray[i],avgArray[i-1])-Math.min(avgArray[i],avgArray[i-1]);
	            }
	            int w = 2;//移动极差的长度。默认值为 2。
	            double avgSumJc = sumJc/((avgArray.length-w+1)*1d);//移动极差平均值
	            double stdev = avgSumJc/SpcCalUtil.D2ConstantNum[w-2];
	
	            CL = SpcCalUtil.ZeroFormat(SpcCalUtil.avage(avgArray),p);//样板平均值
	            //计算均值
	            UCL = SpcCalUtil.ZeroFormat(CL+stdev*3,p);
	            LCL = SpcCalUtil.ZeroFormat(CL-stdev*3,p);
	        }
	        else{
		        CL = SpcCalUtil.ZeroFormat(SpcCalUtil.avage(avgArray),p);//样板平均值
		        //计算均值
		        UCL = SpcCalUtil.ZeroFormat(CL+SpcCalUtil.A2ConstantNum[sampleSize-2]*CL_R,p);
		        LCL = SpcCalUtil.ZeroFormat(CL-SpcCalUtil.A2ConstantNum[sampleSize-2]*CL_R,p);
	        }
        }
        
        Map<String, Object> returnData = new HashMap<String, Object>();
        returnData.put("UCL", UCL);
        returnData.put("CL", CL);
        returnData.put("LCL", LCL);
        return returnData;
	}
	
	/**
	 * 清除判异结果数据 根据项目
	 * @param calId
	 * @return
	 */
	public boolean deleteCheckDataByCalId(String calId){
		String sql2 = "delete from Emesq_SPC_SAMPLE_CHECK where emesq_spc_sample_calc_id=?";
		int r2 = dao.executeSql(sql2, calId);
		return r2>0;
	}
	
	/**
	 * 清除判异结果数据 根据项目
	 * @param configId
	 * @return
	 */
	public boolean deleteCheckData(String configId){
		String sql2 = "delete from Emesq_SPC_SAMPLE_CHECK where emesq_spc_sample_calc_id in (select Emesq_SPC_SAMPLE_CALC_ID from emesq_spc_sample_calc where Emesq_SPC_CK_CONFIG_ID=?)";
		int r2 = dao.executeSql(sql2, configId);
		return r2>0;
	}
	
	/**
	 * 清空样本数据
	 * @param configId
	 */
	public boolean deleteSampleData(String configId){
		String sql1 = "delete from emesq_spc_sample_value where emesq_spc_sample_calc_id in (select Emesq_SPC_SAMPLE_CALC_ID from emesq_spc_sample_calc where Emesq_SPC_CK_CONFIG_ID=?)";
		int r1 = dao.executeSql(sql1, configId);
		String sql2 = "delete from Emesq_SPC_SAMPLE_CHECK where emesq_spc_sample_calc_id in (select Emesq_SPC_SAMPLE_CALC_ID from emesq_spc_sample_calc where Emesq_SPC_CK_CONFIG_ID=?)";
		int r2 = dao.executeSql(sql2, configId);
		String sql3 = "delete from emesq_spc_sample_calc where Emesq_SPC_CK_CONFIG_ID=?";
		int r3= dao.executeSql(sql3, configId);
		return r1>0&&r2>0&&r3>0;
	}
	
	/**
	 * 删除样本数据
	 * @param configId
	 */
	public boolean deleteData(String configId){
		String sql1 = "delete from emesq_spc_sample_value where emesq_spc_sample_calc_id in (select Emesq_SPC_SAMPLE_CALC_ID from emesq_spc_sample_calc where Emesq_SPC_CK_CONFIG_ID=?)";
		int r1 = dao.executeSql(sql1, configId);
		String sql2 = "delete from Emesq_SPC_SAMPLE_CHECK where emesq_spc_sample_calc_id in (select Emesq_SPC_SAMPLE_CALC_ID from emesq_spc_sample_calc where Emesq_SPC_CK_CONFIG_ID=?)";
		int r2 = dao.executeSql(sql2, configId);
		String sql3 = "delete from emesq_spc_sample_calc where Emesq_SPC_CK_CONFIG_ID=?";
		int r3= dao.executeSql(sql3, configId);
		String sql4 = "delete from emesq_spc_er_apply where Emesq_SPC_CK_CONFIG_ID=?";
		int r4= dao.executeSql(sql4, configId);
		String sql5 = "delete from Emesq_SPC_BADPRODUCT where Emesq_SPC_CK_CONFIG_ID=?";
		int r5= dao.executeSql(sql5, configId);
		String sql6 = "delete from Emesq_SPC_CK_CONFIG where Emesq_SPC_CK_CONFIG_ID=?";
		int r6= dao.executeSql(sql6, configId);
		
		return true;
	}
	
	/**
	 * 清空样本值数据 单条
	 * @param configId
	 */
	public boolean deleteSampleValueData(String calcId){
		String sql1 = "delete from emesq_spc_sample_value where emesq_spc_sample_calc_id = ?";
		int r1 = dao.executeSql(sql1, calcId);
		String sql2 = "delete from Emesq_SPC_SAMPLE_CHECK where emesq_spc_sample_calc_id = ?";
		int r2 = dao.executeSql(sql2, calcId);
		String sql3 = "delete from emesq_spc_sample_calc where emesq_spc_sample_calc_id = ?";
		int r3= dao.executeSql(sql3, calcId);
		return r1>0&&r2>0;
	}
	
	/**
	 * 查看判异结果
	 * @param calId
	 * @return
	 */
	public Map<String,Object> viewCheckRs(String calId){
		String sql = "select essc.emesq_spc_sample_check_id,essc.emesq_spc_sample_calc_id,essc.error_info,essc.reason,essc.handle_info,"+
				" (select a.name from ad_user a where a.ad_user_id=essc.handle_user_id) handle_user_name," +
				"to_char(essc.handle_time,'yyyy-MM-dd hh24:mi:ss') handle_time"+
				" from Emesq_SPC_SAMPLE_CHECK essc "+
				" where essc.emesq_spc_sample_calc_id=?";
//		System.out.println(sql);
		return dao.queryUnique(sql, calId);
	}
	
	/**
	 * 处理异常
	 * @param calId
	 * @param unControlReason
	 * @param handleMethod
	 * @param user
	 * @return
	 */
	public boolean handleError(String calId,String unControlReason,String handleMethod,User user){
		String sql = "update Emesq_SPC_SAMPLE_CHECK set reason=?,handle_info=?,HANDLE_USER_ID=?,HANDLE_TIME=now() where emesq_spc_sample_calc_id=?";
		int r = dao.executeSql(sql, unControlReason,handleMethod,user.getId(),calId);
		String updateSql = "update Emesq_Spc_Sample_Calc set STATE=? where emesq_spc_sample_calc_id=?";
		int r2 = dao.executeSql(updateSql,"已处理",calId);
		return r>0&&r2>0;
	}
	
	private boolean checkData(Map<String, Object> arrayDataMap){
        return arrayDataMap==null||Integer.parseInt(arrayDataMap.get("dataSize")+"")==0;
    }
}
